<template>
  <div >
    <el-row>
      <el-col :span="24">
        <el-upload
            class="flex-upload"
            ref="uploadRef"
            :multiple="false"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-remove="clearFile"
            :limit="1"
            :on-exceed="handleExceed"
        >
          <template #trigger>
            <el-button>选择文件</el-button>
          </template>
        </el-upload>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {defineEmits, ref} from 'vue';
import { genFileId } from 'element-plus';
const emit = defineEmits(['read'])

// 定义响应式变量来存储文件内容
const fileContent = ref('');
let file = ref(null)
const uploadRef = ref(null)

const handleFileChange = (UploadFile) => {
  file = UploadFile.raw;
  if (UploadFile) {
    const reader = new FileReader();
    reader.onload = (e) => {
      fileContent.value = e.target.result;
    };
    reader.readAsText(file);
    emit('read', fileContent);
  }
}
// 处理文件选择事件
const handleFileChange1 = (event) => {
  console.log("in file change", event);
  file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      fileContent.value = e.target.result;
    };
    reader.readAsText(file);
    emit('read', fileContent);
  }
};

const clearFile = () => {
  uploadRef.value.clearFiles();
  fileContent.value = '';
  file = null
  console.log("uploadRef:",uploadRef)
}

const handleExceed = (files) => {
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
}
</script>

<style scoped>
.flex-upload {
  display: flex;
  justify-content: center;
}
.flex-upload > .el-upload > .el-upload-list {
  width: 200px
}
</style>
